package edu.zzuli.assistant.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

import edu.zzuli.assistant.service.UserService;
import edu.zzuli.assistant.service.impl.UserServiceImpl;
import edu.zzuli.assistant.until.FileUtil;
import edu.zzuli.assistant.until.StrUtil;

public class UpdateAppAcion extends ActionSupport implements SessionAware{
	public  String version_path = "version.txt";        // app版本路径
	public  String verrsion_temp = "version_temp.txt";  //app版本临时路径
	public  String apkName = "instructor.apk";  //app版本临时路径
	public  String apkName_temp = "temp.apk";  //app版本临时路径
	protected String dirTemp = "temp/"; 
	String savePath;
	private Map<String, Object> session;
	UserService service = new UserServiceImpl();

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	// 跟新app
	public String update() {
		if(session.get("id")!=null){
			savePath = ServletActionContext.getServletContext().getRealPath("/") + "file/";
			if (upLoad()) {
				HttpServletRequest request = ServletActionContext.getRequest();
				String version = request.getParameter("version");
				FileUtil.delete(savePath + apkName); // 删除旧的文件
				FileUtil.reName(savePath + apkName_temp, savePath + apkName);// 重新命名
				version_path = savePath + version_path;
				verrsion_temp = savePath + verrsion_temp;
				FileUtil.writeToText(verrsion_temp, version);
				FileUtil.delete(version_path);
				FileUtil.reName(verrsion_temp, version_path);
				return SUCCESS;
			}
			else{
				return "fail";
			}
		}
		return "fail";
	}
	
	public void  getUpdate(){
		version_path = ServletActionContext.getServletContext().getRealPath("/") + "file/"+version_path; 
		String version = FileUtil.readText(version_path);
		StrUtil.sendMsg(version);
	}
	public boolean upLoad() {
		boolean result = false ;
		HttpServletRequest request = ServletActionContext.getRequest();
    	HttpServletResponse response = ServletActionContext.getResponse(); 
        try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        response.setContentType("text/html; charset=UTF-8");  
        //文件保存目录路径  
        // 临时文件目录   
        String tempPath = ServletActionContext.getServletContext().getRealPath("/") + dirTemp;  
        //创建文件夹  
        File dirFile = new File(savePath);  
        if (!dirFile.exists()) {  
            dirFile.mkdirs();  
        }  
        //创建临时文件夹  
        File dirTempFile = new File(tempPath);  
        if (!dirTempFile.exists()) {  
            dirTempFile.mkdirs();  
        }  
        DiskFileItemFactory  factory = new DiskFileItemFactory();  
        factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时，将产生临时文件并存储于临时目录中。     
        factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。     
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setHeaderEncoding("UTF-8");  
        try {  
            List items = upload.parseRequest(request); 
            Iterator itr = items.iterator();  
            while (itr.hasNext())   
            {  
                FileItem item = (FileItem) itr.next();  
                String fileName = item.getName(); 
                long fileSize = item.getSize();
                if(fileSize>15*1024*1024){
                	return false; // 文件大于15m 阻止上传
                }
                if (!item.isFormField()) {  
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
                   if(fileExt==null || (!"apk".equals(fileExt) )){
                	    //不是apk
                	   return false;
                   }
                    File uploadedFile ;  
                    OutputStream outputStream = null ;  
                    InputStream inputStream = null ;  
                    try{  
                    	uploadedFile = new File(savePath, apkName_temp);  
                        outputStream = new FileOutputStream(uploadedFile);  
                        inputStream = item.getInputStream();  
                        byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度  
                        int length = 0;    
                        while( (length = inputStream.read(buf)) > 0 ){    
                            outputStream.write(buf, 0, length);    
                        }    
                        result = true;
                    }catch(Exception e){  
                        e.printStackTrace();  
                        result = false;
                    }
                    finally{
                        //关闭流    
                        try {
							outputStream.flush();
							outputStream.close();    
							inputStream.close(); 
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}  
                    }
                }            
            }   
        } catch (FileUploadException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return result;
	}
//跳到更新app
	public String toUpdate(){
		if (session.get("id")!=null) {
			return "toUpdate_app";
		}
		return "fail";
	}
}
